<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>报表条件查询</title>
    <link rel="stylesheet" href="/lib/pagination/style/pagination.css">
    <link rel="stylesheet" href="/css/base/base.css?20201106.1">
    <link rel="stylesheet" href="/css/notice/noticeManagement.css">
    <script src="/js/common/language.js"></script>
    <script type="text/javascript" src="/js/jquery/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="/js/base/tablePage.js"></script>
    <script src="/js/base/base.js"></script>
    <script src="/lib/laydate/laydate.js"></script>
    <script src="/lib/jquery.form.min.js"></script>
    <script src="/lib/pagination/js/jquery.pagination.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" src="/lib/highcharts.js"></script>
    <script src="https://cdn.bootcss.com/jspdf/1.5.3/jspdf.debug.js"></script>

    <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/commonTheme/${sessionScope.InterfaceModel}/commonTheme.css"/>

    <style>
        table tbody td {
            text-align: left;
            padding: 10px;
            box-sizing: border-box;
        }

        table tbody td.color {
            padding: 10px 10px 10px 38px;
        }

        input {
            float: none;
        }

        .editAndDelete3 {
            color: red;
        }

        .color {
            /*font-size: 14px;*/
            font-size: 11pt;
            color: #2a588c;
            font-weight: bold;
        }

        table tbody td textarea {
            width: 281px;
            height: 34px;
            line-height: 34px;
            padding-left: 10px;
            outline: none;
            border-radius: 4px;
            vertical-align: middle;
            font-family: "Microsoft Yahei";
        }

        table tbody td a {
            vertical-align: middle;
            font-size: 10pt;
        }

        table tbody td select {
            width: 119px;
            height: 28px;
            border-radius: 4px;
        }

        table tbody td input[type=text] {
            width: 288px;
            height: 32px;
            border-radius: 4px;
            padding-left: 10px;
            box-sizing: border-box;
        }

        .btnsava {
            padding: 5px 30px;
            border-radius: 4px;
            background: #2F8AE3;
            color: #fff;
        }

        #pageTbody tr td {
            text-align: left;
        }

        .head-top {
            width: 100%;
            position: static;
            top: 0px;
            left: 0px;
            height: 45px;
            border-bottom: 1px solid #999;
            border-top: 1px solid #999;
            background: #fff;
            overflow: hidden;
            margin-top: 20px;
            z-index: 9999999;
        }

        .head-top ul {
            padding-left: 10px;
        }

        .head-top ul .head-top-li.active {
            background: #2F8AE3;
            color: #fff;
        }

        .head-top ul .head-top-li {
            height: 26px;
            line-height: 26px;
            margin: 10px 11px 0px 11px;
            padding: 1px 20px;
            font-size: 14px;
            border-radius: 20px;
            cursor: pointer;
        }

        .fl {
            float: left;
        }

        .pagediv table {
            width: 100%;
            margin-top: 20px;
        }

        .pagediv table th {
            background: white;
            line-height: 40px;
            height: 100%;
            border-bottom: 1px #dddddd solid;
            font-size: 13pt;
            color: #2F5C8F;
            font-weight: bold;
            border: 0px;
            padding: 4px;
            box-sizing: border-box;
            text-align: center;
        }

        .pagediv table th:last-child {
            width: 300px;
        }

        .pagediv table td {
            font-weight: normal;
            overflow: hidden;
            white-space: pre;
            height: 40px;
            padding: 4px;
            box-sizing: border-box;
            text-overflow: ellipsis;
            font-size: 11pt;
            text-align: center;
        }

        /*#list{*/
        /*display: none;*/
        /*}*/
        .field {
            width: 150px !important;
        }

        #back {
            /*margin-top:60px;*/
        }

        .back {
            padding: 5px 15px;
            border-radius: 4px;
            background: #2F8AE3;
            color: #fff;
            float: right;
            cursor: pointer;
            margin-right: 20px;
            display: none;
        }

        .tbody tr td {
            border: 1px solid #dddddd;
        }

        #container, #container1, #container2 {
            width: 80%;
            margin: 0 auto;
            height: 500px;
            display: none;
        }

        .pic {
            display: none;
        }

        .pagediv {
            display: none;
        }

        .head-top {
            display: none;
        }

        #picture {
            display: none;
            float: right;
            margin-right: 20px;
            width: 100px;
            height: 30px;
            border-radius: 3px;
        }

    </style>
    <%--<script src="/js/notice/queryAll.js"></script>--%>
</head>
<body>
<div class="container">
    <div class="content">
        <div class="navigation">
            <img src="/img/commonTheme/${sessionScope.InterfaceModel}/gonggaochaxun.png" alt="">
            <h2>报表条件查询</h2>
        </div>
        <div class="query" style="width: 80%;">

            <div class="header">报表条件查询</div>

            <%--<form id="ajaxform" action="">--%>
            <input type="hidden" name="read">
            <input type="hidden" name="sendTime">
            <table style="width: 100%">
                <tbody>

                <tr class="borderNone">
                    <td width="30%" class="color">日期范围：</td>
                    <td width="70%">
                        <input type="text" placeholder="<fmt:message code="doc.th.startDate"/>" name="beginDate"
                               onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})" readonly="readonly"
                               style="width: 155px">
                        <span><fmt:message code="global.lang.to"/></span>
                        <input type="text" placeholder="<fmt:message code="doc.th.endDate"/>" name="endDate"
                               onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})" style="width: 155px"
                               readonly="readonly">
                    </td>
                </tr>
                <tr class="borderNone">
                    <td width="30%" class="color">发布部门范围：</td>
                    <td width="70%">
                        <textarea name="" placeholder="请选择发布部门" class="theControlData" deptId="" readonly="readonly"
                                  id="reles" cols="30" rows="10"></textarea>
                        <a href="javascript:;" class="addroles"><fmt:message code="global.lang.add"/></a>
                        <a href="javascript:;" class="delete"><fmt:message code="global.lang.empty"/></a>

                        <input type="hidden" name="fromId">
                    </td>
                </tr>
                <tr class="borderNone">
                    <td width="30%" class="color">根据角色范围：</td>
                    <td width="70%">
                        <textarea name="" placeholder="请选择角色" class="theControlData" deptId="" readonly="readonly"
                                  id="userPrivs" cols="30" rows="10"></textarea>
                        <a href="javascript:;" class="addPrivs"><fmt:message code="global.lang.add"/></a>
                        <a href="javascript:;" class="deletePrivs"><fmt:message code="global.lang.empty"/></a>

                        <input type="hidden" name="fromId">
                    </td>
                </tr>

                <tr class="borderNone">
                    <td width="30%" class="color">自定义查询条件：</td>
                    <td width="70%" class="search">
                        <%--<input type="text" placeholder="<fmt:message code="new.th.putcontent"/>" name="content">--%>
                    </td>
                </tr>
                <tr class="borderNone">
                    <td colspan="2" style="text-align: center">
                        <a href="javascript:;" class="btnsava query" id="query"><fmt:message
                                code="global.lang.query"/></a>
                        <a href="javascript:;" style="margin-left: 10px" class="btnsava outerport">excel导出</a>
                        <a href="javascript:;" style="margin-left: 10px" class="btnsava outerportpDF">PDF导出</a>

                    </td>
                </tr>
                </tbody>
            </table>
            <%--</form>--%>
        </div>
    </div>

    <div id="list">

        <div class="head-top">
            <ul class="clearfix">
                <li class="fl head-top-li active" data-type="0">数据报表</li>
                <li class="fl head-top-img"><img src="/img/twoth.png" alt=""></li>
                <li class="fl head-top-li" data-type="1">图形报表</li>
            </ul>
        </div>

        <div id="back">

            <%--<span class="back">返回</span>--%>
            <select name="" id="picture">
                <option value="0">饼状图</option>
                <option value="1">柱状图</option>
                <option value="2">折线图</option>
            </select>
        </div>
        <div class="pagediv" id="pdfHtml">
            <table id="showData">
                <thead class="thead" id="th">
                <tr>

                </tr>
                </thead>
                <tbody class="tbody">

                </tbody>
            </table>
        </div>
        <div class="pic">
            <div id="container">

            </div>
            <div id="container1">

            </div>
            <div id="container2">

            </div>
        </div>
    </div>


</div>

<script>
    var rId = $.GetRequest().rId;
    var flowId = $.GetRequest().flowId;
    var arrs = [];
    $(function () {
        $.ajax({
            url: '/workflow/work/getReportById',
            dataType: 'json',
            type: 'get',
            data: {rid: rId},
            success: function (res) {
                var data = res.object;
                var list = data.flowReportResultList;
                var str = "";
                for (var i = 0; i < list.length; i++) {
                    if (list[i].disp_name != undefined) {
                        str += '<div class="tj" style="display: inline-block;margin-left: 5px"><span>' + list[i].disp_name + '</span>:<input type="text" class="field" name="' + list[i].field + '"></div>'
                    }
                }
                $('.search').html(str)
            }
        })
        $('.addroles').click(function () {
            dept_id = 'reles';
            $.popWindow("../../common/selectDept");
        })
        $('.delete').click(function () {
            $('#reles').val('')
            $('#reles').attr('deptId', '')
        })

        $('.addPrivs').click(function () {
            priv_id = 'userPrivs';
            $.popWindow("../../common/selectPriv");
        })
        $('.deletePrivs').click(function () {
            $('#userPrivs').val('')
            $('#userPrivs').attr('userpriv', '')
            $('#userPrivs').attr('privid', '')
        })
        $('.back').click(function () {
            $('.content').show();
            $('.head-top').hide();
            $('.back').hide()
            $('.pagediv').hide();
            $('.pic').hide();
            $('#picture').hide();
        })

        function check(name) {
            if (name == undefined) {
                return ''
            } else {
                return name;
            }
        }

        $('.head-top-li').click(function () {
            var type = $(this).attr('data-type');
            $(this).addClass('active').siblings().removeClass('active');

            if (type == 0) {
                // $('.content').hide();
                $('.head-top').show();
                $('.back').show()
                $('.pagediv').show();
                $('.pic').hide();
                $('#container').hide()
                $('#container1').hide()
                $('#container2').hide()
                $('#picture').hide()
            } else {

                // $('.content').hide();
                $('.head-top').show();
                $('.back').show()
                $('.pagediv').hide();
                $('.pic').show();
                $('#container').show()
                $('#container1').hide()
                $('#container2').hide()
                $('#picture').show()

            }
        })

        $('#picture').change(function () {
            var type = $(this).val()
            if (type == 0) {
                $('#container').show()
                $('#container1').hide()
                $('#container2').hide()
            } else if (type == 1) {
                $('#container').hide()
                $('#container1').show()
                $('#container2').hide()
            } else {
                $('#container').hide()
                $('#container1').hide()
                $('#container2').show()
            }
        })

//        点击查询
        $('#query').click(function () {
            var data = {
                flowId: flowId,
                beginTime: $('[name="beginDate"]').val(),
                endTime: $('[name="endDate"]').val(),
                deptIds: $('#reles').attr('deptId'),
                userPrivs: $('#userPrivs').attr('userpriv'),
                rid: rId
            }
            var arr = [];
            for (var i = 0; i < $('.field').length; i++) {
                arr.push($('.field').eq(i).attr('name'))
            }

            var arrTwo = $.unique(arr)
            var str = ""
            for (var i = 0; i < arrTwo.length; i++) {
                var strTwo = ""
                for (var j = 0; j < $('[name="' + arrTwo[i] + '"]').length; j++) {
                    if ($('[name="' + arrTwo[i] + '"]').eq(j).val() != "") {
                        strTwo += $('[name="' + arrTwo[i] + '"]').eq(j).val() + ','
                    }
                }
                if (strTwo != "") {
                    str += arrTwo[i] + '|' + strTwo + '||'
                }

            }
            data.definds = str;
            data.type = 0;
            $.ajax({
                url: '/workflow/work/queryReport',
                dataType: 'json',
                type: 'get',
                data: data,
                success: function (res) {
                    if (res.flag) {
                        $('.tbody').empty();
                        var datas = res.obj;
                        if (datas.length > 0) {
                            // $('.content').hide();
                            $('.head-top').show();
                            $('.back').show()
                            $('.pagediv').show();
                            $('.pic').hide();
                            var th = ''
                            for (var i = 0; i < datas[0].length; i++) {
                                th += ' <th>' + datas[0][i] + '</th>'
                            }
                            $('.thead tr').html(th)
                            var names = [];
                            var tds = ""

                            var names = [];
                            x = datas[0][0]
                            y = datas[0][1]

                            for (var i = 0; i < datas[1].length; i++) {
                                var obj = {};
                                var list = datas[1][i].dispList.length
                                obj.name = datas[1][i].disp_name;
                                obj.y = datas[1][i].dispCount;
                                if (i != (datas[1].length - 1)) {
                                    arrs.push(obj);
                                }
                                names.push(obj.name);
                                for (var j = 0; j < list; j++) {
                                    tds = '<tr>' +
                                        function () {
                                            if (list > 1) {
                                                if (j == 0) {
                                                    return '<td rowspan="' + list + '">' + datas[1][i].disp_name + '</td>'
                                                } else {
                                                    return ''
                                                }
                                            } else {
                                                return '<td rowspan="' + list + '">' + datas[1][i].disp_name + '</td>'
                                            }
                                        }()
                                        + function () {
                                            if (datas[1][i].dispCount != "" && datas[1][i].dispCount != undefined) {
                                                if (list > 1) {
                                                    if (j == 0) {
                                                        return '<td rowspan="' + list + '">' + datas[1][i].dispCount + '</td>'
                                                    } else {
                                                        return ''
                                                    }
                                                } else {
                                                    return '<td rowspan="' + list + '">' + datas[1][i].dispCount + '</td>'
                                                }
                                            } else {
                                                $('.head-top-li').eq(1).hide();
                                                return ""
                                            }
                                        }() +
                                        function () {
                                            var str = ""
                                            for (var m = 0; m < datas[1][i].dispList[j].length; m++) {
                                                str += '<td>' + checkNull(datas[1][i].dispList[j][m]) + '</td>'
                                            }
                                            return str;
                                        }()
                                        + '</tr>'
                                    $('.tbody').append(tds)
                                }


                            }
                            pie(arrs, x, y)
                            colum(arrs, names, x, y)
                            getzh(arrs, names, x, y)
                        } else {
                            $.layerMsg({content: '暂无数据', icon: 6})
                        }
                    } else {
                        $.layerMsg({content: '暂无数据', icon: 6})
                    }
                }
            })
        })
        //        点击导出
        $('.outerport').click(function () {
            var arr = [];
            for (var i = 0; i < $('.field').length; i++) {
                arr.push($('.field').eq(i).attr('name'))
            }
            var arrTwo = $.unique(arr)
            var str = ""
            for (var i = 0; i < arrTwo.length; i++) {
                var strTwo = ""
                for (var j = 0; j < $('[name="' + arrTwo[i] + '"]').length; j++) {
                    if ($('[name="' + arrTwo[i] + '"]').eq(j).val() != "") {
                        strTwo += $('[name="' + arrTwo[i] + '"]').eq(j).val() + ','
                    }
                }
                if (strTwo != "") {
                    str += arrTwo[i] + '|' + strTwo + '||'
                }
            }
            window.location.href = '/workflow/work/queryReport?flowId=' + flowId + '&beginTime=' + $('[name="beginDate"]').val() + '&endTime=' + $('[name="endDate"]').val() + '&deptIds=' + $('#reles').attr('deptId') + '&rid=' + rId + '&definds=' + str + '&type=1'
        })

        //pdf导出
        $('.outerportpDF').click(function () {
            var myTable = document.getElementById("showData");
            var a = myTable.rows.length;
            if (a < 2) {
                alert("请先查询！")
            }
            html2canvas(
                document.getElementById("pdfHtml"),

                {

                    dpi: 5000,//导出pdf清晰度

                    onrendered: function (canvas) {

                        var contentWidth = canvas.width;

                        var contentHeight = canvas.height;


                        //一页pdf显示html页面生成的canvas高度;

                        var pageHeight = contentWidth / 595.28 * 841.89;

                        //未生成pdf的html页面高度

                        var leftHeight = contentHeight;

                        //pdf页面偏移

                        var position = 0;

                        //html页面生成的canvas在pdf中图片的宽高（a4纸的尺寸[595.28,841.89]）

                        var imgWidth = 595.28;

                        var imgHeight = 595.28 / contentWidth * contentHeight;


                        var pageData = canvas.toDataURL('image/jpeg', 1.0);

                        var pdf = new jsPDF('', 'pt', 'a4');


                        //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)

                        //当内容未超过pdf一页显示的范围，无需分页

                        if (leftHeight < pageHeight) {

                            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);

                        } else {

                            while (leftHeight > 0) {

                                pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)

                                leftHeight -= pageHeight;

                                position -= 841.89;

                                //避免添加空白页

                                if (leftHeight > 0) {

                                    pdf.addPage();

                                }

                            }

                        }

                        pdf.save('工作流报表.pdf');

                    },

                    //背景设为白色（默认为黑色）

                    background: "#fff"

                })
        })


    })

    function pie(data, x, y) {
        $('#container').highcharts({
            chart: {
                type: 'pie',
                backgroundColor: 'rgba(0,0,0,0)'
            },
            title: {
                text: ''
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                x: 15,
                verticalAlign: 'top',
                y: 65,
//                    floating: true,
            },
            options3d: {
                enabled: true,
                alpha: 45,
                beta: 0
            },
            exporting: {
                enabled: false
            },
            credits: {
                enabled: false
            },
            plotOptions: {
                pie: {
//                        innerSize:'30',
//                        allowPointSelect:true,
                    cursor: 'pointer',
                    depth: 35,
                    dataLabels: {
                        enabled: true,
//                        distance: -20,
                        format: '<b style="font-size:14px;color:#fff;font-weight: normal"><span>{point.name}</span>:<span>{point.y}</span> </b>',
                        connectorWidth: 1,
//                            distance:5
                    },
//                        formatter:function(){
//                            return '<b>'+this.point.name+'</b>:'+this.point.percentage.toFixed(2)+"%";
//                        },
//                        format: '{y}%',
//                showInLegend:true
                },

            },
            tooltip: {
                headerFormat:
                    '<span style="font-size:11px">{point.name}</span><br>',
                pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b><br/>'
            },
            series: [{
                name: x,
                type: 'pie',
//                    colorByPoint: true,
                data: data
            }]
        });
    }

    function colum(data, name, x, y) {
        $('#container1').highcharts({
            chart: {
                type: 'column',
                backgroundColor: 'rgba(0,0,0,0)'
            },
            title: {
                text: ''
            },
//        legend: {
//            layout: 'vertical',
//            align: 'right',
//            x: 15,
//            verticalAlign: 'top',
//            y: 65,
////                    floating: true,
//        },
            xAxis: {
                categories: name,
                crosshair: true
            },
            yAxis: {
                min: 0,
                title: {
                    text: y
                }
            },
            options3d: {
                enabled: true,
                alpha: 45,
                beta: 0
            },
            exporting: {
                enabled: false
            },
            credits: {
                enabled: false
            },
            plotOptions: {
                pie: {
//                        innerSize:'30',
//                        allowPointSelect:true,
                    cursor: 'pointer',
                    depth: 35,
                    dataLabels: {
                        enabled: true,
                        distance: -20,
                        format: '<b style="font-size:14px;color:#fff;font-weight: normal">' + this.point + ' </b>',
                        connectorWidth: 1,
//                            distance:5
                    },
//                        formatter:function(){
//                            return '<b>'+this.point.name+'</b>:'+this.point.percentage.toFixed(2)+"%";
//                        },
//                        format: '{y}%',
//                showInLegend:true
                },

            },
            tooltip: {
                headerFormat:
                    '<span style="font-size:11px">{point.name}</span><br>',
                pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b><br/>'
            },
            series: [{
                name: x,
                type: 'column',
//                    colorByPoint: true,
                data: data
            }]
        });
    }

    function getzh(data, name, x, y) {
        $('#container2').highcharts({
            chart: {
                zoomType: 'xy'
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            xAxis: [{
                categories: name,
                crosshair: true
            }],
            yAxis: [{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                },
                title: {
                    text: y,
                    style: {
                        color: Highcharts.getOptions().colors[1]
                    }
                }
            }],
            tooltip: {
                shared: true
            },
            legend: {
                layout: 'vertical',
                align: 'left',
                x: 120,
                verticalAlign: 'top',
                y: 100,
                floating: true,
                backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
            },
            series: [{
                name: x,
                type: 'spline',
                data: data,
//                tooltip: {
//                    valueSuffix: '°C'
//                }
            }]
        });
    }

    function checkNull(data) {
        if (data == "null") {
            return '';
        } else {
            return data;
        }

    }

</script>
</body>
</html>